package com.webserver_v2.core;

import com.sun.prism.shader.Solid_RadialGradient_REFLECT_AlphaTest_Loader;
import com.webserver_v2.http.HttpServletRequest;
import com.webserver_v2.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;
    private static File rootDir;
    private static File staticDir;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    static {
        try {
            rootDir = new File( ClientHandler.class.getClassLoader()
                    .getResource(".").toURI());
           staticDir = new File(rootDir,"static");

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    public void run(){
        try {
            //1.解析请求(读取浏览器发送的请求)
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);
            //2.处理请求(获取请求中的uri)
            String path = request.getUri();

            //3.发送响应
            File file = new File(staticDir,path);

            if (file.isFile()){
               response.setContentFile(file);
            }else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
               file = new File(staticDir,"root/404.html");
               response.setContentFile(file);
            }
            //发送状态行
            //发送响应头
            //发送响应正文(将index.html文件所有数据发送)
            response.response();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
